const http=require("http");
const server=http.createServer((req,res)=>{
    res.setHeader("content-type","application/json;charset=utf-8");
    //路由
    req.path=req.url.split("?")[0];
    switch (req.path){
        case "/":
            let data={
                msg:"请求根目录",
            }
            res.end(JSON.stringify(data))
            break;
        case "/login":
            const users = [ { username: 'admin', password: 'password123' } ];
            //获取参数
            let url="http://localhost:8080"+req.url;
            let myURL=new URL(url);
            let username=myURL.searchParams.get("username");
            let password=myURL.searchParams.get("password");
            //判断用户是否存在
            let flag=false;
            users.forEach(user=>{
                if(user.password===password&&user.username===username){
                    flag=true;
                }
            })
            if(flag==true){
                let data={
                    msg:"登录成功",
                    code:200,
                    username:username
                }
                res.end(JSON.stringify(data))
            }else{
                let data={
                    msg:"登录失败",
                    code:401
                }
                res.end(JSON.stringify(data))
            }
            break;
        default:
            break;
    }
})
server.listen(9000,()=>{
    console.log("server start up...");
})                                  